package com.yf.cmw.broadcast;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.SystemClock;
import android.util.Log;

import com.yf.cmw.constant.BussConstant;
import com.yf.cmw.presenter.MainPresenter;

import static android.content.Context.ALARM_SERVICE;

public class AlarmReceiver extends BroadcastReceiver {
    private static final String TAG = "AlarmReceiver";
    int time_interval = BussConstant.TIME_INTERVAL;
    private MainPresenter mainPresenter = null;
    private Context mcontext = null;

    public static boolean adSwitch = true; //广告请求开关[true:开启,false:关闭]

    @Override
    public void onReceive(Context context, Intent intent) {
        String msg = "AlarmReceiver start ... ";
        Log.e(TAG, msg);
        MainPresenter.writeLogRecord(msg);
        this.mcontext = context;
        this.mainPresenter = new MainPresenter(context);
        time_interval = mainPresenter.getRoundTime();
        Intent _intent = new Intent(context,AlarmReceiver.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, _intent, 0);

        AlarmManager alarmManager = (AlarmManager) context.getSystemService(ALARM_SERVICE);
        // 重复定时任务
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            alarmManager.setExactAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + time_interval, pendingIntent);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            alarmManager.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + time_interval, pendingIntent);
        }
        execute();
        msg = "AlarmReceiver end ... ";
        Log.e(TAG, msg);
       // MainPresenter.writeLogRecord(msg);
    }

    /**
     * 获取广告资源
     */
    private void execute(){
        String msg = "AlarmReceiver execute getAD Start ... ";
        Log.e(TAG, msg);
       // MainPresenter.writeLogRecord(msg);
        if(!adSwitch){
            Log.e(TAG, String.format("广告下载开关%s",(adSwitch ? "已开启":"已关闭")));
            return;
        }
        mainPresenter.getAD();
        msg = "AlarmReceiver execute getAD End ... ";
        Log.e(TAG, msg);
       // MainPresenter.writeLogRecord(msg);
    }
}
